<?php

namespace app\api\service;

use app\common\Base;
use think\Config;
use think\Controller;


class DadaService extends Controller
{

    private $app_key;   //达达开发者app_key

    private $app_secret;    //达达开发者app_secret

    private $url;   //api url地址

    private $v = "1.0";   //api版本

    private $format = "json";   //数据格式

    private $source_id;   // 商户ID

    private $httpTimeout = 5;   //http request timeout;

    private $status;   //请求响应返回的数据状态

    private $code;   //请求响应返回的code

    private $msg;    //请求响应返回的信息

    private $result;   //请求响应返回的结果

    private $excepetMsg;   // 异常信息

    public function __construct($config)
    {
        $this->app_key = Config::get('imdada.app_key');
        $this->app_secret = Config::get('imdada.app_secret');
        $this->url = $config['url'];
        $this->source_id = $config['source_id'];
    }

    // 请求Api
    public function makeRequest($data)
    {
        $reqParams = $this->bulidRequestParams(json_encode($data));
        $base = new Base();
        $resp = $base->_requestPost($this->url, json_encode($reqParams, true), false, ['Content-Type:application/json']);
        return $resp;
    }

    // 必备数据信息
    public function bulidRequestParams($body)
    {
        $requestParams = array();
        $requestParams['app_key'] = $this->app_key;
        $requestParams['body'] = $body;
        $requestParams['format'] = $this->format;
        $requestParams['v'] = $this->v;
        $requestParams['source_id'] = $this->source_id;
        $requestParams['timestamp'] = time();
        $requestParams['signature'] = $this->_sign($requestParams);
        return $requestParams;
    }

    // 签名
    public function _sign($data)
    {
        ksort($data);   //1.升序排序
        $args = "";   //2.字符串拼接
        foreach ($data as $key => $value) {
            $args .= $key . $value;
        }
        $args = $this->app_secret . $args . $this->app_secret;
        $sign = strtoupper(md5($args));
        return $sign;
    }

    //回调签名
    public function callback_sign($client_id, $order_id, $update_time)
    {
        $data['client_id'] = $client_id;
        $data['order_id'] = $order_id;
        $data['update_time'] = $update_time;
        asort($data);   //1.升序排序
        $args = "";   //2.字符串拼接

        foreach ($data as $key => $value) {
            $args .= $value;
        }
        $sign = md5($args);
        return $sign;
    }

}
